<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>图片上传模拟</title>
  </head>
  <body>
    <h2>上传你的头像</h2>
    <!-- 图片上传表单 -->
    <form id="uploadForm">
      <!-- 文件选择框：只允许图片 -->
      <label for="avatar">选择图片：</label>
      <input type="file" id="avatar" name="avatar" accept="image/*" required /> <br /><br />
      <!-- 上传按钮 -->
      <button type="submit">上传图片</button>
      <button type="button" onclick="resetForm()">重置</button>
    </form>
    <!-- 图片预览区域 -->
    <div id="preview" style="margin-top: 20px">
      <p>图片预览：</p>
      <img id="previewImage" src="" alt="预览" style="max-width: 300px; max-height: 300px; display: none; border: 1px solid #ccc" />
      <p id="noImage">暂无图片</p>
    </div>
    <!-- 上传状态显示 -->
    <div id="status"></div>

    <script>
      const form = document.getElementById("uploadForm");
      const fileInput = document.getElementById("avatar");
      const previewImage = document.getElementById("previewImage");
      const noImage = document.getElementById("noImage");
      const statusDiv = document.getElementById("status");
      // 当用户选择文件时，预览图片
      fileInput.addEventListener("change", function () {
        const file = this.files[0];
        if (file) {
          const reader = new FileReader();

          reader.onload = function (e) {
            previewImage.src = e.target.result; // 设置图片源
            previewImage.style.display = "block";
            noImage.style.display = "none";
          };

          reader.readAsDataURL(file); // 读取为 Data URL
        } else {
          clearPreview();
        }
      });

      // 提交表单（模拟上传）
      form.addEventListener("submit", function (e) {
        e.preventDefault(); // 阻止默认提交（防止页面刷新）
        const file = fileInput.files[0];
        if (!file) {
          statusDiv.innerHTML = '<span style="color: red;">请先选择图片！</span>';
          return;
        }
        // 模拟上传过程
        statusDiv.innerHTML = `正在上传图片：${file.name}（${(file.size / 1024).toFixed(1)} KB）...`;

        // 模拟网络延迟1.5秒
        setTimeout(() => {
          statusDiv.innerHTML = `<span style="color: green;">✅ 图片 "${file.name}" 上传成功！</span>`;
        }, 1500);
      });

      // 重置表单和预览
      function resetForm() {
        form.reset();
        clearPreview();
        statusDiv.innerHTML = "";
      }

      // 清除预览
      function clearPreview() {
        previewImage.src = "";
        previewImage.style.display = "none";
        noImage.style.display = "block";
      }
    </script>
  </body>
</html>
